import {  IApiRes, Profile } from "@/types/data";
import { getProfile, removeProfile, setProfile } from "@/utils/profile";
import request from "@/utils/request";
import { defineStore } from "pinia";

export default defineStore('user', {
  state() {
    return {
      profile: getProfile() as Profile //用户登录信息
    }
  },
  actions: {
    // 用户登录
    async login(data: { account: string, password: string}) {
      const res = await request.post<IApiRes<Profile>>('/login', data)
      this.profile = res.data.result
      // 持久化保存
      setProfile(res.data.result)
    },

    // 获取短信验证码
    async sendCode(mobile: string) {
      const res = await request.get('/login/code', {
        params: { mobile }
      })
      // this.profile = res.data.result
      console.log(res.data.result);
    },
    async mobileLogin(mobile: string, code: string) {
      const res = await request.post<IApiRes<Profile>>('/login/code', {
        mobile,
        code
      })
      // 1. 保存用户信息到 state 中
      this.profile = res.data.result
    },

    // 退出登录
    logOut() {
      // 删除pinia
      this.profile = {} as Profile
      // 清空本地
      removeProfile()
    },

    // 使用openId去登录
    async loginQQ(openId: string) {
      const res = await request.post<IApiRes<Profile>>('/login/social', {
        unionId: openId,
        source: 6
      })
      this.profile = res.data.result
      // 持久化保存
      setProfile(res.data.result)
    },

    // 绑定qq的短信验证码
    async sendQQBindMsg(mobile: string) {
      await request.get('/login/social/code', {
        params: {
          mobile
        }
      })
    },

     // 绑定当前的QQ和账号
     async qqBindLogin(openId: string, mobile: string, code: string) {
      const res = await request.post<IApiRes<Profile>>('/login/social/bind', {
        mobile,
        code,
        unionId: openId
      })
      // 1. 保存用户信息到 state 中
      this.profile = res.data.result
      // 2. 持久化
      setProfile(res.data.result)
    },
  },
  // 持久化保存-插件
  // persist: {
  //   enabled: true
  //   // key: ''
  // }
})
